<template>
  <div class="dialog">
    <el-dialog :title="title" :visible.sync="visible" :close-on-click-modal="false" width="65%" top="20vh">
      <el-form :model="createForm" style="padding-right: 20px;" label-width="120px" label-suffix=":" :rules="rules"
        ref="createForm">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="调度名称" prop="applyName">
              <el-input v-model.trim="createForm.applyName" placeholder="请输入调度名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调度门店" prop="storeName">
              <el-input v-model.trim="createForm.storeName" placeholder="" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="调度时间" prop="time">
              <el-date-picker v-model="createForm.time" size="small" type="daterange" value-format="yyyy-MM-dd"
                unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="onTimeChange"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="技能名称" prop="skillTypeList">
              <el-cascader ref="cascader" :key="resetCascader" placeholder="请选择技能名称" v-model="createForm.skillTypeList"
                :props="props" @change="onSkillChange" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="被调度门店" prop="storeConfirmId">
              <el-select ref="storeSelect" v-model="createForm.storeConfirmId" filterable placeholder="请选择调度门店"
                @change="onStoreChange" style="width: 100%;">
                <el-option v-for="item in storeList" :key="item.storeId" :label="item.storeName" :value="item.storeId"
                  style="height: 50px;">
                  <span class="name">{{ item.storeName }}</span>
                  <span class="addr">{{ "电话：" + item.phoneNum + "，地址：" + item.address }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调度技师" prop="empId">
              <el-select ref="empSelect" v-model="createForm.empId" placeholder="请选择调度技师" @change="onEpmChange"
                style="width: 100%;">
                <el-option v-for="item in userList" :key="item.empId" :label="item.empName" :value="item.empId"
                  style="height: 50px;">
                  <span class="name">{{ item.empName }}</span>
                  <span class="addr">{{ "电话：" + item.phonenum + "，技能信息：" + item.skillInfo }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="调度说明" prop="applyRemark">
              <el-input v-model.trim="createForm.applyRemark" placeholder="请输入调度说明"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeNetWorker()">关 闭</el-button>
        <el-button type="primary" @click="confirmData('createForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Vue from 'vue'
import {
  storeSkillTypeLazyTree,
  findNearByStoreList,
  findEmpListByStoreId
} from '@/api/index'
import {
  technicianDispatchApply,
  technicianDispatchUpdate
} from '@/api/business'
export default {
  name: "TechnicianDialog",
  data() {
    return {
      title: "",
      isEdit: false,
      visible: false,
      createForm: {},
      storeList: [],
      userList: [],
      resetCascader: 0,
      props: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          setTimeout(async () => {
            const res = await this.getTreeByParentCode(node)
            return resolve(res)
          })
        }
      },
      rules: {
        applyName: [
          { required: true, message: "请输入调度名称", trigger: "blur" },
          { max: 20, message: "字数不超过20", trigger: "blur" },
        ],
        time: [
          { required: true, message: "请选择调度时间", trigger: "blur" },
        ],
        skillTypeList: [
          { required: true, message: "请选择技能名称", trigger: 'blur' },
        ],
        storeConfirmId: [
          { required: true, message: "请选择被调度门店", trigger: "blur" },
        ],
        empId: [
          { required: true, message: "请选择调度技师", trigger: "blur" },
        ]
      },
    }
  },
  created() { },
  mounted() { },
  methods: {
    add() {
      this.title = "新增";
      this.isEdit = false;
      this.createForm = {};
      this.createForm.storeName = Vue.ls.get("ORG_NAME");
      this.initTree();
      this.visible = true;
    },
    edit(val) {
      this.title = "编辑";
      this.isEdit = true;
      this.createForm = Object.assign({}, val);
      this.initTree();
      this.visible = true;
      this.resetCascader++;
      this.createForm.time = [];
      this.createForm.time[0] = this.createForm.dispatchStartTime;
      this.createForm.time[1] = this.createForm.dispatchEndTime;
      this.initUser();
    },
    initTree() {
      findNearByStoreList({
        page: 1,
        size: 100
      }).then(res => {
        if (res.data.code == 0) {
          this.storeList = res.data.data.record
        }
      })
    },
    getTreeByParentCode(node) {
      return new Promise((resolve, reject) => {
        let params = {}
        if (node.data) {
          params = { parentId: node.data.value }
        }
        storeSkillTypeLazyTree(params).then(res => {
          if (res.data.code == 0) {
            const nodes = Array.from(res.data.data).map(item => ({
              value: item.id,
              label: item.skillTypeName,
              leaf: !item.hasChildren
            }))
            resolve(nodes)
          }
        })
      })
    },
    onTimeChange() {
      this.initUser();
    },
    onSkillChange() {
      this.initUser();
      if (this.$refs.cascader.getCheckedNodes()[0]) {
        console.log(this.$refs.cascader.getCheckedNodes()[0].label)
        this.createForm.skillTypeName = this.$refs.cascader.getCheckedNodes()[0].label;
      }
    },
    onStoreChange() {
      this.initUser();
      this.$nextTick(() => {
        console.log(this.$refs.storeSelect.selected.label)
        this.createForm.storeConfirmName = this.$refs.storeSelect.selected.label;
      });
    },
    onEpmChange() {
      this.$nextTick(() => {
        console.log(this.$refs.storeSelect.selected.label)
        this.createForm.empName = this.$refs.empSelect.selected.label;
      });
    },
    initUser() {
      if (this.createForm.skillTypeList && this.createForm.time && this.createForm.storeConfirmId) {
        let param = {
          startTime: this.createForm.time[0],
          endTime: this.createForm.time[1],
          skillTypeId: this.createForm.skillTypeList[this.createForm.skillTypeList.length - 1],
          storeId: this.createForm.storeConfirmId,
          page: 1,
          size: 100
        }
        findEmpListByStoreId(param).then(res => {
          if (res.data.code == 0) {
            this.userList = res.data.data.record
          }
        })
      }
    },
    confirmData(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          this.createForm.skillType = this.createForm.skillTypeList.join(",");
          this.createForm.dispatchStartTime = this.createForm.time[0];
          this.createForm.dispatchEndTime = this.createForm.time[1];
          if (this.createForm.id) {
            technicianDispatchUpdate(this.createForm).then((res) => {
              const data = res.data
              if (data.code == 0) {
                this.$message.success('修改成功');
                this.$emit('ok');
                this.closeNetWorker();
              } else {
                this.$message.error(data.data || '修改失败')
              }
            })
          } else {
            technicianDispatchApply(this.createForm).then((res) => {
              const data = res.data
              if (data.code == 0) {
                this.$message.success('新增成功');
                this.$emit('ok');
                this.closeNetWorker();
              } else {
                this.$message.error(data.data || '新增失败')
              }
            })
          }
        }
      });
    },
    closeNetWorker() {
      this.createForm = {};
      this.visible = false;
    }
  }
};
</script>
<style scoped lang="less">
.content {
  height: 400px;
  overflow: auto;
}

.name {
  float: left;
  position: relative;
  display: block;
}

.addr {
  float: left;
  position: absolute;
  display: block;
  margin-top: 20px;
  font-size: 13px;
  color: #b4b4b4;
}
</style>
